const validate = require("validate.js");
const {ValidationError} = require("../utils/errors");
const fs = require("fs");
const {addMessageDao, getMessageByPageDao, deleteMessageDao} = require("../dao/messageDao");
const {getBlogByIdDao} = require("../dao/blogDao");
const {formatResponse, handleDataPattern} = require("../utils/tool");
const dir = './public/static/avatar';

/**
 * 读取一个目录下的文件数量
 * @param dir
 * @returns {Promise<unknown>}
 */
async function readDirLength(dir) {
    return new Promise(resolve => {
        fs.readdir(dir, (err, files) => {
            if (err) {
                throw new Error(err)
            }
            resolve(files)
        })
    })
}

// 添加留言或者评论
module.exports.addMessageService = async function (newMessage) {
    const messageRule = {
        nickname: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        content: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        blogId: {
            type: 'number'
        }
    }
    const validateResult = validate.validate(newMessage, messageRule)
    if (!validateResult) {
        newMessage.blogId = newMessage.blogId ? newMessage.blogId : null
        newMessage.createDate = Date.now()
        // 生成随机头像
        const files = await readDirLength(dir);
        const randomIndex = Math.floor(Math.random() * files.length);
        newMessage.avatar = '/static/avatar/' + files[randomIndex];
        const data = await addMessageDao(newMessage);
        // 如果是评论 则更新博客评论数
        if (newMessage.blogId) {
            const blogData = await getBlogByIdDao(newMessage.blogId)
            blogData.commentNumber++;
            await blogData.save()
        }
        return formatResponse(0, '', data);
    } else {
        throw new ValidationError('数据验证失败', validateResult)
    }
}

// 查询留言或者评论
module.exports.getMessageByPageService = async function (pageInfo) {
    const data = await getMessageByPageDao(pageInfo);
    const rows = handleDataPattern(data.rows)
    return formatResponse(0, '', {
        rows,
        total: data.count
    });
}

// 删除留言或者评论
module.exports.deleteMessageService = async function (id) {
    await deleteMessageDao(id);
    return formatResponse(0, '删除成功', {});
}